﻿using ThingsEdge.Router.Interfaces;

namespace Digitalmes.Infrastructure.Scada;

/// <summary>
/// SCADA 程序启动后台服务。
/// </summary>
internal sealed class ScadaStartupHostedService(IExchange exchange,
    IOptions<ScadaConfig> config,
    ILogger<ScadaStartupHostedService> logger) : IHostedService
{
    public async Task StartAsync(CancellationToken cancellationToken)
    {
        if (!config.Value.IsAutoStartup)
        {
            return;
        }

        try
        {
            await Task.Delay(2000, cancellationToken).ConfigureAwait(false); // 延迟启动

            if (!exchange.IsRunning)
            {
                logger.LogInformation("SCADA 自动服务启动中。。。");

                await exchange.StartAsync();

                logger.LogInformation("SCADA 服务已启动");
            }
        }
        catch (Exception ex) 
        {
            logger.LogError(ex, "[AppStartupHostedService] SCADA 服务启动失败。");
        }
    }

    public async Task StopAsync(CancellationToken cancellationToken)
    {
        if (config.Value.IsAutoStartup && exchange.IsRunning)
        {
            await exchange.ShutdownAsync();

            logger.LogInformation("SCADA 服务已关闭");
        }
    }
}
